import Vue from 'vue'
import vm from '@/main'

// const IP = 'http://192.168.153.197:8081'
// const baseUrl = "http://192.168.153.197:8081"
// 'jumeng-server'
const IP = 'https://group-drama.suanbankeji.com/jumeng_admin/'
const baseUrl = "https://xcx.suanbankeji.com"
const websocket = "wss://xcx.suanbankeji.com/websocket/"

export {
	baseUrl,
	websocket
}

// 跳转方便统一改样式
Vue.prototype.$goPage = function(url, option) {
	console.log(url, option)
	option = option || {};
	option.url = url;
	uni.navigateTo(option);
}

Vue.prototype.$goPageShock = function(url, option) {
	uni.vibrateShort()
	console.log(url, option)
	option = option || {};
	option.url = url;
	uni.navigateTo(option);
}

Vue.prototype.$login = function() {
	return new Promise((resolve, reject) => {
		// if (vm.vuex_user.id == undefined) {
		//用户登录
		vm.code = ''
		uni.login({
			provider: 'weixin',
			success: (loginRes) => {
				vm.code = loginRes.code
			},

		});
		getUserInfo()

		function getUserInfo() {
			//获取用户信息，存入缓存

			uni.getUserProfile({
				desc: '获取用户头像',
				lang: 'zh_CN',
				success: async (infoRes) => {
					let res = await vm.$u.api.wxlogin({
						code: vm.code
					})
					vm.$u.vuex('vuex_token', res.data.token)

					let res1 = await vm.$u.api.getUserInfo({
						sessionKey: res.data.sessionKey,
						encryptedData: infoRes.encryptedData,
						iv: infoRes.iv
					})
					if (res1.code === 200) {
						vm.$u.vuex('vuex_user', res1.data)
					}
				}
			});
		}
		// }
		resolve();
	});

}

//页面跳转，判断用户是否登录
Vue.prototype.$goPageIsLoginOk = function(url, option) {
	option = option || {};
	option.url = url;


	if (vm.vuex_user.id == undefined) {
		//用户登录
		vm.code = ''
		uni.login({
			provider: 'weixin',
			success: (loginRes) => {
				vm.code = loginRes.code
			},

		});
		getUserInfo()

		function getUserInfo() {
			//获取用户信息，存入缓存

			uni.getUserProfile({
				desc: '获取用户头像',
				lang: 'zh_CN',
				success: async (infoRes) => {
					let res = await vm.$u.api.wxlogin({
						code: vm.code
					})
					vm.$u.vuex('vuex_token', res.data.token)

					let res1 = await vm.$u.api.getUserInfo({
						sessionKey: res.data.sessionKey,
						encryptedData: infoRes.encryptedData,
						iv: infoRes.iv
					})
					if (res1.code === 200) {
						vm.$u.vuex('vuex_user', res1.data)
						uni.navigateTo(option);
					}
				}
			});
		}
	} else {
		uni.navigateTo(option);
	}

}

// 重定向跳转方便统一改样式
Vue.prototype.$redirectTo = function(url, option) {
	option = option || {};
	option.url = url;
	uni.redirectTo(option);
}

Vue.prototype.$redirectToIsLoginOk = function(url, option) {
	option = option || {};
	option.url = url;


	if (vm.vuex_user.id == undefined) {
		//用户登录
		vm.code = ''
		uni.login({
			provider: 'weixin',
			success: (loginRes) => {
				vm.code = loginRes.code
			},

		});
		getUserInfo()

		function getUserInfo() {
			//获取用户信息，存入缓存

			uni.getUserProfile({
				desc: '获取用户头像',
				lang: 'zh_CN',
				success: async (infoRes) => {
					let res = await vm.$u.api.wxlogin({
						code: vm.code
					})
					vm.$u.vuex('vuex_token', res.data.token)

					let res1 = await vm.$u.api.getUserInfo({
						sessionKey: res.data.sessionKey,
						encryptedData: infoRes.encryptedData,
						iv: infoRes.iv
					})
					if (res1.code === 200) {
						vm.$u.vuex('vuex_user', res1.data)
						uni.redirectTo(option);
					}
				}
			});
		}
	} else {
		uni.redirectTo(option);
	}

}


Vue.prototype.$navigateBack = function() {
	uni.navigateBack()
}

Vue.prototype.$textToast = (text) => {
	uni.showToast({
		title: text,
		icon: "none"
	})
}

Vue.prototype.$Toast = (text, icon, duration, successFn) => {
	uni.showToast({
		title: text,
		icon: icon,
		duration: duration,
		success: () => {
			setTimeout(successFn, duration)
		}
	})
}

Vue.prototype.$successToast = (text) => {
	uni.showToast({
		title: text
	})
}

Vue.prototype.$message = {
	info(title, options) {
		options = options || {};
		uni.showToast({
			title,
			duration: options.duration || 2000
		});
	},
	error() {
		return this.info(...arguments)
	}
}

// Vue.prototype.$request = request

Vue.prototype.$getWeekDate = function(date) {
		var now = new Date(date);
		var day = now.getDay();
		var weeks = new Array("周日", "周一", "周二", "周三", "周四", "周五", "周六");
		var week = weeks[day];
		return week;
	},

	Vue.prototype.$dateFormat = function(timestamp, formats) {
		// formats格式包括
		// 1. Y-m-d
		// 2. Y-m-d H:i:s
		// 3. Y年m月d日
		// 4. Y年m月d日 H时i分
		// 5. Y.m.d
		// 6. 自定义格式
		formats = formats || 'Y-m-d';

		var zero = function(value) {
			if (value < 10) {
				return '0' + value;
			}
			return value;
		};

		var myDate = timestamp ? new Date(timestamp) : new Date();

		var year = myDate.getFullYear();
		var month = zero(myDate.getMonth() + 1);
		var day = zero(myDate.getDate());

		var hour = zero(myDate.getHours());
		var minite = zero(myDate.getMinutes());
		var second = zero(myDate.getSeconds());

		return formats.replace(/Y|m|d|H|i|s/ig, function(matches) {
			return ({
				Y: year,
				m: month,
				d: day,
				H: hour,
				i: minite,
				s: second
			})[matches];
		});
	}

//金额格式转换
Vue.prototype.$amountCvs = function(num, n) {
	num = num === '' ? 0 : num
	// num 金额
	// n 保留小数位数
	n = n || 2 //设置保留的小数位数
	num = parseFloat((num + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
	if (num == 'NaN') {
		return 0
	}
	var l = num.split(".")[0].split("").reverse();
	var r = num.split(".")[1];
	var t = "";
	for (var i = 0; i < l.length; i++) {
		t += l[i];
	}
	return t.split("").reverse().join("") + "." + r;
}

//dateTimeStamp是一个时间毫秒，注意时间戳是秒的形式，在这个毫秒的基础上除以1000，就是十位数的时间戳。13位数的都是时间毫秒。

Vue.prototype.$timeago = function(dateTimeStamp) {
	var minute = 1000 * 60; //把分，时，天，周，半个月，一个月用毫秒表示
	var hour = minute * 60;
	var day = hour * 24;
	var week = day * 7;
	var halfamonth = day * 15;
	var month = day * 30;
	var now = new Date().getTime(); //获取当前时间毫秒
	var diffValue = now - dateTimeStamp; //时间差


	var result
	if (diffValue < 0) {
		return;
	}
	var minC = diffValue / minute; //计算时间差的分，时，天，周，月
	var hourC = diffValue / hour;
	var dayC = diffValue / day;
	var weekC = diffValue / week;
	var monthC = diffValue / month;
	if (monthC >= 1 && monthC <= 3) {
		result = " " + parseInt(monthC) + "月前"
	} else if (weekC >= 1 && weekC <= 3) {
		result = " " + parseInt(weekC) + "周前"
	} else if (dayC >= 1 && dayC <= 6) {
		result = " " + parseInt(dayC) + "天前"
	} else if (hourC >= 1 && hourC <= 23) {
		result = " " + parseInt(hourC) + "小时前"
	} else if (minC >= 1 && minC <= 59) {
		result = " " + parseInt(minC) + "分钟前"
	} else if (diffValue >= 0 && diffValue <= minute) {
		result = "刚刚"
	} else {
		var datetime = new Date();
		datetime.setTime(dateTimeStamp);
		var Nyear = datetime.getFullYear();
		var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
		var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
		var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
		var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
		var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
		result = Nyear + "-" + Nmonth + "-" + Ndate
	}
	return result;
}
//是否有域名
Vue.prototype.$isHttp = (str) => {
	var reg = new RegExp("http")
	if (reg.test(str)) {
		return str
	} else {
		return IP + str
	}
}


/**
 * 数组元素交换位置
 * @param {array} arr 数组
 * @param {number} index1 添加项目的位置
 * @param {number} index2 删除项目的位置
 * index1和index2分别是两个数组的索引值，即是两个要交换元素位置的索引值，如1，5就是数组中下标为1和5的两个元素交换位置
 */
Vue.prototype.$swapArray = (arr, index1, index2) => {
	arr[index1] = arr.splice(index2, 1, arr[index1])[0];
	return arr;
}

/**
 * 复制，设置剪贴板内容
 * @param {string} content 要复制的内容
 */
Vue.prototype.$copy = (content) => {
	uni.setClipboardData({
		data: content,
		success: (res) => {
			vm.$textToast('复制成功')
		}
	});
}

/**
 * 下载资源到本地
 * @param {string} url 要下载的内容
 */
Vue.prototype.$downloadFile = (url) => {
	uni.downloadFile({
		url: url, //仅为示例，并非真实的资源
		success: (res) => {
			if (res.statusCode === 200) {
				uni.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,
					success: function() {
						vm.$textToast('保存成功')
					}
				});
			}
		}
	});
}

/**
 * 小数相加
 * @param {number} num1 小数
 * @param {number} num2 小数
 * 先判断俩个相加数谁的小数点后位数多，以多的为准，值乘以10的小数位的幂数，相加以后，再除以10的小数位的幂数
 */
Vue.prototype.$addNum = (num1, num2) => {
	var sq1, sq2, m;
	try {
		sq1 = num1.toString().split(".")[1].length;
	} catch (e) {
		sq1 = 0;
	}
	try {
		sq2 = num2.toString().split(".")[1].length;
	} catch (e) {
		sq2 = 0;
	}
	m = Math.pow(10, Math.max(sq1, sq2));
	return (num1 * m + num2 * m) / m;
}

/**
 * 小数相减
 * @param {number} num1 小数
 * @param {number} num2 小数
 * 先判断俩个相加数谁的小数点后位数多，以多的为准，值乘以10的小数位的幂数，相加以后，再除以10的小数位的幂数
 */
Vue.prototype.$subNum = (num1, num2) => {
	var sq1, sq2, m;
	try {
		sq1 = num1.toString().split(".")[1].length;
	} catch (e) {
		sq1 = 0;
	}
	try {
		sq2 = num2.toString().split(".")[1].length;
	} catch (e) {
		sq2 = 0;
	}
	m = Math.pow(10, Math.max(sq1, sq2));
	return (num1 * m - num2 * m) / m;

}


/**
 * 比较时间大小
 * @param {string} date1 时间1
 * @param {string} date2 时间2
 * 
 */
Vue.prototype.$compareDate = (date1, date2) => {
	var oDate1 = new Date(date1);
	var oDate2 = new Date(date2);
	if (oDate1.getTime() > oDate2.getTime()) {
		return true; //第一个大
	} else {
		return false; //第二个大
	}
}
